const fs = require('fs');
const { getScript } = require('./AddScript');
const { getBoxCollider } = require('./BoxCollider');
const { getButton } = require('./Button');
const { getDistanceJoint } = require('./DistanceJoint');
const { getPhysicsCircleCollider } = require('./PhysicsCircleCollider');
const { getPhysicsPolygonCollider } = require('./PhysicsPolygonCollider');
const { getPrismaticJoint } = require('./PrismaticJoint');
const { getRevoluteJoint } = require('./RevoluteJoint');
const { getRigidBody } = require('./RigidBody');
const { getRopeJoint } = require('./RopeJoint');
const { getSprite } = require('./Sprite');
const { getSpSkeleton } = require('./SpSkeleton');
global.finialInfo = [];
global.UnityNode;
global.curID = 0;
global.isShowId = false;
global.mapID = {};
global.cocosPath = ""; //填写对应cocos的assets路径
global.cocosPrefabPath = ""; //填写对应cocos的assets路径
var unityList = [];
var prefabNames = [];
var unityPath = "";
var animPath = "E:/workobj/11/assets/animClip/";
//读取cocos的meta文件
global.readFileMeta = (name) => {
  return JSON.parse(fs.readFileSync(name + ".meta", "utf8"));
}
readFile = () => {
  var config = JSON.parse(fs.readFileSync("./config.json", "utf8"));
  global.cocosPath = config.cocosPath;
  global.cocosPrefabPath = config.cocosPrefabPath;
  unityPath = config.unityPath;
  const arr = fs.readdirSync(unityPath);
  arr.forEach((item) => {
    if (item.indexOf(".meta") == -1) {
      console.log(item);
      let d = fs.readFileSync(unityPath + "/" + item, "utf8");
      unityList.push(JSON.parse(d));
      prefabNames.push(item.split(".")[0]);
    }

  });
}

initData = (i) => {
  global.finialInfo = [];
  global.UnityNode = unityList[i];
  global.curID = 0;
  global.mapID = {
    SpSkeleton:[],
    SpriteRenderer: [],
    Animation: [],
    RigidBody: [],
    PhysicsPolygonCollider: [],
    PhysicsCircleCollider: [],
    BoxCollider:[],
    DistanceJoint: [],
    RevoluteJoint:[],
    RopeJoint:[],
    PrismaticJoint:[],
    CCButton: [],
    Prefab: [],
    Script: [],
    ComPrefab: {
      Sr: [],
      Anim: []
    }
  };
}
initRoot = () => {
  for (var i = 0; i < unityList.length; i++) {
    initData(i);
    finialInfo.push(addRootPrefab());
    getAllID();
    getNode();
    //添加组件
    getSprite();
    getRigidBody();
    getPhysicsPolygonCollider();
    getPhysicsCircleCollider();
    getBoxCollider();
    getDistanceJoint();
    getButton();
    getSpSkeleton();
    getRevoluteJoint();
    getPrismaticJoint();
    getRopeJoint();
    getScript();
    getPrefab();
    writeFile(i);
  }

}
var curIndex;
//提前设置组件索引值
getAllID = () => {
  curIndex = global.UnityNode.length;
  setMapID("SpriteRenderer");
  setMapID("AnimClip");
  setMapID("RigidBody");
  setMapID("PhysicsPolygonCollider");
  setMapID("PhysicsCircleCollider");
  setMapID("BoxCollider");
  setMapID("DistanceJoint");
  setMapID("CCButton");
  setMapID("SpSkeleton");
  setMapID("RevoluteJoint");
  setMapID("PrismaticJoint");
  setMapID("RopeJoint");
  setMapID("Script");
  setMapID("Prefab");
}
setMapID = (type) => {
  for (var i = 0; i < global.UnityNode.length; i++) {
    var d = global.UnityNode[i];
    switch (type) {
      case "SpSkeleton":
        if (d.SpSkeleton.Add) {
          curIndex++;
          global.mapID.SpSkeleton.push(curIndex);
        }
        break;
      case "SpriteRenderer":
        if (d.SpritePath != "") {
          curIndex++;
          global.mapID.SpriteRenderer.push(curIndex);
        }
        break;
      case "AnimClip":
        if (d.AnimClip.length > 0) {
          curIndex++;
          global.mapID.Animation.push(curIndex);
        }
        break;
      case "RigidBody":
        if (d.RigidBody.Add) {
          curIndex++;
          global.mapID.RigidBody.push(curIndex);
        }
        break;
      case "PhysicsPolygonCollider":
        for (var j = 0; j < d.PhysicsPolygonCollider.length; j++) {
          if (d.PhysicsPolygonCollider[j].Add) {
            curIndex++;
            global.mapID.PhysicsPolygonCollider.push(curIndex);
          }
        }
        break;
      case "PhysicsCircleCollider":
        if (d.PhysicsCircleCollider.Add) {
          curIndex++;
          global.mapID.PhysicsCircleCollider.push(curIndex);
        }
        break;
      case "BoxCollider":
        if (d.BoxCollider.Add) {
          curIndex++;
          global.mapID.BoxCollider.push(curIndex);
        }
        break;
      case "DistanceJoint":
        for (var j = 0; j < d.DistanceJoint.length; j++) {
          if (d.DistanceJoint[j].Add) {
            curIndex++;
            global.mapID.DistanceJoint.push(curIndex);
          }
        }
        break;
      case "RevoluteJoint":
        if (d.RevoluteJoint.Add) {
          curIndex++;
          global.mapID.RevoluteJoint.push(curIndex);
        }
        break;
      case "PrismaticJoint":
        if (d.PrismaticJoint.Add) {
          curIndex++;
          global.mapID.PrismaticJoint.push(curIndex);
        }
        break;
      case "RopeJoint":
        if (d.RopeJoint.Add) {
          curIndex++;
          global.mapID.RopeJoint.push(curIndex);
        }
        break;
      case "CCButton":
        if (d.CCButton.Add) {
          curIndex++;
          global.mapID.CCButton.push(curIndex);
        }
        break;
      case "Script":
        for (var j = 0; j < d.Script.length; j++) {
          if (d.Script[j].Add) {
            curIndex++;
            global.mapID.Script.push(curIndex);
          }
        }
        break;
      case "Prefab":
        curIndex++;
        global.mapID.Prefab.push(curIndex);
        break;
    }

  }
}
//添加所有节点
getNode = () => {
  var spIndex = 0;
  var animIndex = 0;
  var rigidbodyIndex = 0;
  var physicsPolygonColliderIndex = 0;
  var physicsCircleColliderIndex = 0;
  var boxColliderIndex = 0;
  var distanceJointIndex = 0;
  var cCButtonIndex = 0;
  var spSkeletonIndex = 0;
  var scriptIndex = 0;
  var prefabIndex = 0;
  var revoluteJointIndex = 0;
  var prismaticJointIndex = 0;
  var ropeJointIndex = 0;
  for (var i = 0; i < global.UnityNode.length; i++) {
    var d = global.UnityNode[i];
    var parent = null;
    if (d.ParentId != -1) parent = { "__id__": d.ParentId };
    var child = [];
    if (d.childIDs.length > 0) {
      for (var j = 0; j < d.childIDs.length; j++) {
        child.push({
          "__id__": d.childIDs[j]
        }
        );
      }
    }
    var component = [];
    if (d.SpritePath != "") {
      component.push({
        "__id__": mapID.SpriteRenderer[spIndex]
      });
      spIndex++;
    }
    if (d.AnimClip.length > 0) {
      component.push({
        "__id__": global.mapID.Animation[animIndex]
      });
      animIndex++;
    }
    if (d.RigidBody.Add) {
      component.push({
        "__id__": global.mapID.RigidBody[rigidbodyIndex]
      });
      rigidbodyIndex++;
    }
    for (var j = 0; j < d.PhysicsPolygonCollider.length; j++) {
      if (d.PhysicsPolygonCollider[j].Add) {
        component.push({
          "__id__": global.mapID.PhysicsPolygonCollider[physicsPolygonColliderIndex]
        });
        physicsPolygonColliderIndex++;
      }
    }
    if (d.PhysicsCircleCollider.Add) {
      component.push({
        "__id__": global.mapID.PhysicsCircleCollider[physicsCircleColliderIndex]
      });
      physicsCircleColliderIndex++;
    }
    if (d.BoxCollider.Add) {
      component.push({
        "__id__": global.mapID.BoxCollider[boxColliderIndex]
      });
      boxColliderIndex++;
    }
    if (d.SpSkeleton.Add) {
      component.push({
        "__id__": global.mapID.SpSkeleton[spSkeletonIndex]
      });
      spSkeletonIndex++;
    }
    if (d.RevoluteJoint.Add) {
      component.push({
        "__id__": global.mapID.RevoluteJoint[revoluteJointIndex]
      });
      revoluteJointIndex++;
    }
    if (d.PrismaticJoint.Add) {
      component.push({
        "__id__": global.mapID.PrismaticJoint[prismaticJointIndex]
      });
      prismaticJointIndex++;
    }
    if (d.RopeJoint.Add) {
      component.push({
        "__id__": global.mapID.RopeJoint[ropeJointIndex]
      });
      ropeJointIndex++;
    }
    for (var j = 0; j < d.DistanceJoint.length; j++) {
      if (d.DistanceJoint[j].Add) {
        component.push({
          "__id__": global.mapID.DistanceJoint[distanceJointIndex]
        });
        distanceJointIndex++;
      }
    }
    for (var j = 0; j < d.Script.length; j++) {
      if (d.Script[j].Add) {
        component.push({
          "__id__": global.mapID.Script[scriptIndex]
        });
        scriptIndex++;
      }
    }
    if (d.CCButton.Add) {
      component.push({
        "__id__": global.mapID.CCButton[cCButtonIndex]
      });
      cCButtonIndex++;
    }
    var prefabId = global.mapID.Prefab[prefabIndex];
    prefabIndex++;
    global.curID++;
    global.finialInfo.push(addNode(parent, child, component, prefabId,d));
  }
}
//添加所有节点预制体信息
getPrefab = () => {
  for (var i = 0; i < global.UnityNode.length; i++) {
    global.curID++;
    global.finialInfo.push(addPrefabInfo());
  }
}
//写入预制体
writeFile = (index) => {
  var finial = global.cocosPrefabPath;
  var isJude = false;  //是否覆盖
  if (isJude) {
    if (fs.existsSync(finial + prefabNames[index] + '.prefab')) {

    } else {
      fs.writeFile(finial + prefabNames[index] + '.prefab', JSON.stringify(finialInfo), (err) => {
        if (err) {
          console.error(err);
        }
        console.log("生成" + prefabNames[index] + "成功");
      });
    }
  } else {
    fs.writeFile(finial + prefabNames[index] + '.prefab', JSON.stringify(finialInfo), (err) => {
      if (err) {
        console.error(err);
      }
      console.log("生成" + prefabNames[index] + "成功");
    });
  }

}
//添加预制体根节点
addRootPrefab = () => {
  var d = {
    "__type__": "cc.Prefab",
    "_name": "",
    "_objFlags": 0,
    "__editorExtras__": {
    },
    "_native": "",
    "data": {
      "__id__": 1
    },
    "optimizationPolicy": 0,
    "asyncLoadAssets": false,
    "readonly": false,
  };
  if (global.isShowId) d["ID"] = global.curID;
  return d;
}
addPrefabInfo = (rootID = 1, assetID = 0) => {
  var d = {
    "__type__": "cc.PrefabInfo",
    "root": {
      "__id__": rootID
    },
    "asset": {
      "__id__": assetID
    },
    "fileId": "",
    "sync": false
  }
  if (global.isShowId) d["ID"] = global.curID;
  return d;
}
//添加节点
addNode = (parent, children, component, prefabId,data) => {
  var d = {
    "__type__": "cc.Node",
    "_name": data.Name,
    "_objFlags": 0,
    "_parent": parent,
    "_children": children,
    "_active": data.Active,
    "_components": component,
    "_prefab": {
      "__id__": prefabId
    },
    "_opacity": 255,
    "_color": {
      "__type__": "cc.Color",
      "r": 255,
      "g": 255,
      "b": 255,
      "a": 255
    },
    "_contentSize": {
      "__type__": "cc.Size",
      "width": data.Size.x,
      "height": data.Size.y
    },
    "_anchorPoint": {
      "__type__": "cc.Vec2",
      "x": 0.5,
      "y": 0.5
    },
    "_trs": {
      "__type__": "TypedArray",
      "ctor": "Float64Array",
      "array": [
        data.Pos.x.toFixed(2),
        data.Pos.y.toFixed(2),
        0,
        0,
        0,
        0,
        1,
        data.Scale.x,
        data.Scale.y,
        1
      ]
    },
    "_eulerAngles": {
      "__type__": "cc.Vec3",
      "x": data.Euler.x,
      "y": data.Euler.y,
      "z": data.Euler.z
    },
    "_skewX": 0,
    "_skewY": 0,
    "_is3DNode": false,
    "_groupIndex": 0,
    "groupIndex": 0,
    "_id": ""
  }
  if (global.isShowId) d["ID"] = global.curID;
  return d;
}
//读取unity文件
readFile();
//初始化生成
initRoot();

